package parser;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.List;

import net.htmlparser.jericho.Source;
import sadxmlreader.LeerXml;
import sadxmlreader.TemplateStructure;

public class WikiParser {
	
	

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		
		double t1, t2;
        t1 = System.currentTimeMillis();
		
		URL url= new URL("https://wiki.sei.cmu.edu/sad/index.php/The_Java_Pet_Store_SAD");
     
		Source source=new Source(url);
		
		String urlBase= url.getProtocol()+"://"+url.getHost();
		generateStructure(source,urlBase);
		t2= System.currentTimeMillis();
		
		System.out.println("Tiempo de ejecucion: "+(t2-t1)/1000.0);

	}


	
	private static void generateStructure(Source source, String urlBase) {
	
		List<TemplateStructure> templateFormat = new LeerXml().getPlainStructure();
		Sad sad = new Sad(urlBase,templateFormat,source);	
		
		sad.generate();
		
		if(sad.isSadGenerated()){
			StringBuilder textToFile = getTextToFile(sad);
		
			write(textToFile);
		}
			
		}



	private static void write(StringBuilder textToFile) {
		
		FileWriter fw=null;
		try {
			fw = new FileWriter("SadPlano.txt");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    BufferedWriter bw = new BufferedWriter(fw);
	    PrintWriter salida = new PrintWriter(bw);
	    salida.println(textToFile);
	    salida.close();
		
	}



	private static StringBuilder getTextToFile(Sad sad) {
		
		
		StringBuilder text=new StringBuilder();
		
		text.append(sad.getCompleteText());
			
		return text;
	}
	
	

}
